<?php

namespace apps\marriage\core\service;

use apps\marriage\core\model\MarketingActivity;
use think\Exception;
use vm\com\BaseService;
use vm\org\lock\DisLockFactory;

class MarketingActivityService extends BaseService
{
    /**
     * @return MarketingActivity
     */
    protected function getModel()
    {
        return new MarketingActivity();
    }

    /**
     * @return VipCardService
     */
    private function getVipCardService()
    {
        return service('VipCard', SERVICE_NAMESPACE);
    }

    /**
     * @return MemberProfileService
     */
    private function getMemberProfileService()
    {
        return service('MemberProfile', SERVICE_NAMESPACE);
    }

    /**
     * @return UserPlatformService
     */
    private function getUserPlatformService()
    {
        return service('UserPlatform', SERVICE_NAMESPACE);
    }

    /**
     * @return SiteConfigService
     */
    private function getSiteConfigService()
    {
        return service('SiteConfig', SERVICE_NAMESPACE);
    }

    /**
     * @return MarketingActivityJoinerService
     */
    private function getMarketingActivityJoinerService()
    {
        return service('MarketingActivityJoiner', SERVICE_NAMESPACE);
    }

    public function save(array $data)
    {
        if($data['id'] == 0) {
            return $this->create($data);
        } else {
            return $this->updateByPk($data);
        }
    }

    public function format(array $data)
    {
        if($data['vip_card_id'] > 0) {
            $data['vip_card'] = $this->getVipCardService()->getByPk($data['vip_card_id']);
            $data['vip_card'] = $this->getVipCardService()->format($data['vip_card']);
            $data['vip_card_name'] = $data['vip_card']['name'];
        } else {
            $data['vip_card_name'] = '';
            $data['vip_card'] = null;
        }
        return $data;
    }

    public function onJoin($userId, $activityId)
    {
        $lockKey = 'join_marketing_activity:' . $activityId;
        $lock = DisLockFactory::instance()->lock($lockKey, 2000);
        if(!$lock) {
            throw new Exception('请重试');
        }
        try {
            $activity = $this->getByPk($activityId);
            if($activity['enable'] == 0) {
                throw new Exception('活动已下线');
            }
            $nowtime = time();
            if($activity['begin_time'] > $nowtime) {
                throw new Exception('活动未开始');
            }
            if($activity['end_time'] < $nowtime) {
                throw new Exception('活动已结束');
            }
            if($activity['realname_auth_required'] == 1) {  //  需要实名认证
                $memberProfile = $this->getMemberProfileService()->getByUserId($userId);
                if($memberProfile['realname_auth_status'] == 0) {
                    throw new Exception('请先完成实名认证', ERROR_REALNAME_AUTH_REQUIRED);
                }
            }
            if($activity['subscribe_mp_required'] == 1) {       // 需关注公众号
                $appId = $this->getSiteConfigService()->getValueByCode('weixin_mp_app_id');
                $userPlatform = $this->getUserPlatformService()->getByUserIdWithAppid($appId, $userId);
                if(empty($userPlatform) || $userPlatform['is_subscribed'] == 0) {
                    throw new Exception('请先关注公众号', ERROR_SUBSCRIBE_MP_REQUIRED);
                }
            }
            $marketingActivityJoinerService = $this->getMarketingActivityJoinerService();
            if($marketingActivityJoinerService->count([
                'activity_id' => $activityId,
                'user_id' => $userId
            ]) >= $activity['times']) {
                throw new Exception('您已参加过该活动');
            }

            if($marketingActivityJoinerService->count([
                    'activity_id' => $activityId
                ]) >= $activity['max_joiner']) {
                throw new Exception('活动已圆满结束');
            }

            $marketingActivityJoinerService->create([
                'activity_id' => $activityId,
                'user_id' => $userId,
                'join_time' => time()
            ]);
            if($activity['vip_card_id'] > 0) {
                $vipCard = $this->getVipCardService()->getByPk($activity['vip_card_id']);
                // 会员权益
                if($vipCard['vip_level'] > 0) {
                    $this->getMemberProfileService()->updateVipLevel($userId, $vipCard['vip_level'], $vipCard['expire_days'] * 3600 * 24);
                }
            }
        } catch (Exception $e) {
            throw $e;
        } finally {
            DisLockFactory::instance()->unlock($lockKey);
        }
    }
}